package top.yxqz.servlet;


import org.apache.commons.beanutils.BeanUtils;
import top.yxqz.user.Student;
import top.yxqz.util.JDBC;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Mr.余
 * @date 2022/11/16
 * @package top.yxqz.servlet
 */
@WebServlet("/studentlogin")
public class StudentLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        String req_coding = context.getInitParameter("req_coding");
        String resp_coding = context.getInitParameter("resp_coding");
        request.setCharacterEncoding(req_coding);
        response.setContentType(resp_coding);

        PrintWriter writer = response.getWriter();
//        连接mysql
        try {
            Student student = new Student();

            BeanUtils.populate(student, request.getParameterMap());

//            从域对象里拿到匹配的真实的验证码
            int[] vcodes = (int[]) context.getAttribute("vcodes");
            String vcode   = student.getVcode();
            StringBuffer vodes_data = new StringBuffer();
            for (int code : vcodes
            ) {
                vodes_data.append(code);
            }
            System.out.println("用户输入的code：" + vcode);
            System.out.println("StringBuffer:" + vodes_data);

            if (!String.valueOf(vodes_data).equals(vcode)) {
//            idea：ctrl+alt+M
//            eclipse：shift+alt+M
                message("校验码", response, context, writer);
                return;
            }


//            JDBC来自于本项目中的jdbc模块
            Connection connection = JDBC.getConnection();
            if (connection != null) {
//                登录
                ResultSet res = login(connection, student);
                if (res.next()) {
//                    登录成功，跳转到登录成功的页面
                    String contextPath = context.getContextPath();
                    response.sendRedirect(contextPath + "/html/succee.html");
                } else {
                    message("用户名或者密码", response, context, writer);
                }


            }
        } catch (SQLException e) {
            writer.println("<hr>");
            writer.println("你的JDBC连接失败，请查看后端（StudentServlet）的第41行代码");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    /**
     * 错误提示
     *
     * @param msg
     * @param response
     * @param context
     * @param writer
     */
    private void message(String msg, HttpServletResponse response, ServletContext context, PrintWriter writer) {
        writer.println("【" + msg + "】校验失败，3秒自动跳转到登录页面，请重新登录");
        String contextPath = context.getContextPath();
        response.setHeader("Refresh", "3;" + contextPath + "/login.html");
        return;
    }

    private ResultSet login(Connection connection, Student student) throws SQLException {
        String sql = "SELECT * FROM stu WHERE username =? AND password=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, student.getUserName());
        ps.setString(2, student.getPassword());
        ResultSet res = ps.executeQuery();
        return res;
    }
}
